package dbutils

import (
	"gorm.io/gorm"
	gormlog "gorm.io/gorm/logger"
	"local.public/params"
	"reflect"
	"strings"
)

type ModelTableNameStu interface {
	TableName() string
}

func GetTableName(pModel interface{}) string {
	sTableName := ""
	if _, ok := pModel.(ModelTableNameStu); ok {
		sTableName = pModel.(ModelTableNameStu).TableName()
	} else {
		sTableName = reflect.TypeOf(pModel).Name()
	}
	return sTableName
}

// ParseSqlPartText sql文本中对参数的文本化处理
func ParseSqlPartText(partsql string, avars ...interface{}) string {
	return gormlog.ExplainSQL(partsql, nil, `'`, avars...)
}
func QueryWithPagingParam(gormdb *gorm.DB, qryparam *params.PagingParams, defaultOrder string) {
	if qryparam != nil {
		if qryparam.PageSize != -1 {
			iPageSize := qryparam.PageSize
			if qryparam.PageSize == 0 {
				iPageSize = 10
				qryparam.PageSize = iPageSize
			}
			gormdb = gormdb.Limit(iPageSize)
			iPageNum := qryparam.PageNum
			if qryparam.PageNum <= 0 {
				iPageNum = 1
				qryparam.PageNum = iPageNum
			}
			iOffset := (iPageNum - 1) * iPageSize
			gormdb = gormdb.Offset(iOffset)
		}
		if qryparam.Order != "" {
			orderFieldArr := strings.Split(qryparam.Order, ",")
			for _, oneOrderField := range orderFieldArr {
				sTmpOrderField := strings.Trim(oneOrderField, " ")
				if strings.HasPrefix(sTmpOrderField, "-") {
					sTmpOrderField = sTmpOrderField[1:]
					gormdb = gormdb.Order(sTmpOrderField + " desc")
				}
			}
		} else if defaultOrder != "" {
			gormdb = gormdb.Order(defaultOrder)
		} else {
			gormdb = gormdb.Order("id asc")
		}
	} else {
		if defaultOrder != "" {
			gormdb = gormdb.Order(defaultOrder)
		} else {
			gormdb = gormdb.Order("id asc")
		}
	}

	return
}

func QueryWithoutPagingParam(gormdb *gorm.DB, qryparam *params.PagingParams, defaultOrder string) {
	if qryparam != nil && qryparam.Order != "" {
		orderFieldArr := strings.Split(qryparam.Order, ",")
		for _, oneOrderField := range orderFieldArr {
			sTmpOrderField := strings.Trim(oneOrderField, " ")
			if strings.HasPrefix(sTmpOrderField, "-") {
				sTmpOrderField = sTmpOrderField[1:]
				gormdb = gormdb.Order(sTmpOrderField + " desc")
			}
		}
	} else if defaultOrder != "" {
		gormdb = gormdb.Order(defaultOrder)
	}
	return
}
